<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>哈希表</h1>
<script>

    class HashTable{ // 字典
        constructor() {
            this.table = {}
        }
        // 对所有的key值都过一遍 变成字符串
        toStrFn(item){
            if(item === null){
                return 'null'
            }else if(item === undefined){
                return "undefined"
            }else if(typeof item === 'string' || item instanceof String){
                return item
            }
            return JSON.stringify(item)
        }
        hashCode(key){
            let tableKey = this.toStrFn(key)
            let hash = 5381
            for(let i=0;i<tableKey.length;i++){
                hash = (hash * 33) + tableKey.charCodeAt(i)
            }
            return hash % 1013
        }
        set(key, value){
            if(key != null && value !=null){
                let position = this.hashCode(key)
                this.table[position] = new ValuePair(key,value)
                return true
            }
            return false
        }
        get(key){
          return this.table[this.hashCode(key)]?.value
        }
        remove(key){ // 删除属性
            let res = this.table[this.hashCode(key)]
            if(res != null){
                delete this.table[this.hashCode(key)]
                return true
            }
            return false
        }


    }
    class ValuePair{
        constructor(key,value) {
            this.key = key
            this.value = value
        }
    }
    let myData = new HashTable()
    myData.set('name','aaaaa')
    myData.set({a:1},'bbbb')
    console.log(myData)
    console.log(myData.get('name'),myData.get({a:1}),myData.get(''))
    console.log(myData.remove('name'))
</script>
</body>
</html>
